package com.hxq.chatdemo.service;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

@Service
public class WebSocketService {

    private static final ConcurrentHashMap<Channel, String> ONLINE_WS_MAP = new ConcurrentHashMap<>();

    public void connect(Channel channel) {
        ONLINE_WS_MAP.put(channel,channel.id().asShortText());
    }

    public void removed(Channel channel) {
        ONLINE_WS_MAP.remove(channel);
    }

    public void sendMsg(String msg) {
        ONLINE_WS_MAP.forEach(((channel, id) -> {
            channel.writeAndFlush(new TextWebSocketFrame(msg));
        }));
    }

    public ConcurrentHashMap<Channel, String> getChannels(){
        return ONLINE_WS_MAP;
    }

}
